<template>
  <div class="login-container">
    <el-card class="login-card" :body-style="{ padding: '20px' }">
      <h2 class="login-title">登录</h2>
      <el-form ref="loginForm" :model="loginForm" :rules="rules" label-width="80px">
        <el-form-item label="用户名" prop="name">
          <el-input v-model="loginForm.name" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="loginForm.password" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item label="验证码" prop="captcha" class="captcha-item">
          <el-row :gutter="20">
            <el-col :span="16" :pull="8">
              <el-input v-model="loginForm.captcha" @keyup.enter.native="login" placeholder="请输入验证码"></el-input>
            </el-col>
            <el-col :span="8" :pull="6">
              <span class="captcha-question">{{ captcha.question }}</span>
            </el-col>
          </el-row>
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="6" :offset="2">
            <el-form-item class="button-group">
              <el-button type="primary" class="center-button" @click="login">登录</el-button>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item class="button-group">
              <el-button type="primary" class="center-button" @click="openRegisterDialog">注册</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- Registration Dialog -->
    <el-dialog :visible.sync="registerDialogVisible" title="用户注册" @closed="resetRegisterForm">
      <el-form ref="elForm" :model="formData" :rules="registerRules" size="mini" label-width="99px">
        <el-form-item label="用户名" prop="name">
          <el-input v-model="formData.name" placeholder="请输入用户名" clearable prefix-icon='el-icon-user'
                    :style="{width: '100%'}"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="formData.password" placeholder="请输入密码" clearable show-password
                    :style="{width: '100%'}"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="formData.sex" size="medium">
            <el-radio v-for="(item, index) in sexOptions" :key="index" :label="item.value"
                      :disabled="item.disabled">{{item.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="formData.email" placeholder="请输入邮箱地址" clearable :style="{width: '100%'}">
          </el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="formData.phone" placeholder="请输入手机号" :maxlength="11" show-word-limit clearable
                    prefix-icon='el-icon-mobile' :style="{width: '100%'}"></el-input>
        </el-form-item>
        <el-form-item label="出生日期" prop="birthday">
          <el-date-picker v-model="formData.birthday" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                          :style="{width: '100%'}" placeholder="请选择出生日期" clearable></el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {login} from "@/http/login/get";
import {register} from "@/http/login/post";

export default {
  data() {
    return {
      loginForm: {
        name: '',
        password: '',
        captcha: ''
      },
      rules: {
        name: [{required: true, message: '请输入用户名', trigger: 'blur'}],
        password: [{required: true, message: '请输入密码', trigger: 'blur'}],
        captcha: [{required: true, message: '请输入验证码', trigger: 'blur'}]
      },
      captcha: {
        question: '',
        answer: ''
      },

      registerDialogVisible: false,
      formData: {
        name: 'test',
        password: '111',
        sex: 1,
        email: '2090@qq.com',
        phone: '13776599878',
        birthday: '2000-01-01',
      },
      registerRules: {
        name: [{
          required: true,
          message: '请输入用户名',
          trigger: 'blur'
        }],
        password: [{
          required: true,
          message: '请输入密码',
          trigger: 'blur'
        }],
        sex: [{
          required: true,
          message: '性别不能为空',
          trigger: 'blur'
        }],
        email: [{
          required: true,
          message: '请输入邮箱地址',
          trigger: 'blur'
        }],
        phone: [{
          required: true,
          message: '请输入手机号',
          trigger: 'blur'
        }, {
          pattern: /^1(3|4|5|7|8|9)\d{9}$/,
          message: '手机号格式错误',
          trigger: 'blur'
        }],
        birthday: [{
          required: true,
          message: '请选择出生日期',
          trigger: 'blur'
        }],
      },
      sexOptions: [{
        "label": "男",
        "value": 1
      }, {
        "label": "女",
        "value": 0
      }],
    };
  },
  methods: {
    generateCaptcha() {
      const num1 = Math.floor(Math.random() * 10);
      const num2 = Math.floor(Math.random() * 10);
      this.captcha.question = `${num1} + ${num2}`;
      this.captcha.answer = num1 + num2;
    },
    openRegisterDialog() {
      this.registerDialogVisible = true;
    },
    resetRegisterForm() {
      this.formData = {};
    },
    login() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          if (Number(this.loginForm.captcha) === this.captcha.answer) {
            login(this.loginForm).then(response => {
              if (response.data.code == 200) {
                this.$message.success(response.data.msg);
                const token = response.data.data; // 从响应中获取token
                localStorage.setItem('token', token); // 存储token到localStorage
                localStorage.removeItem('menuData'); // 清除权限
                this.$root.$emit('login-successful'); // 发起事件
                this.$router.push('/user')
              } else {
                this.$message.error(response.data.msg);
              }
            });
          } else {
            this.$message.error('验证码错误，请重新输入');
            this.generateCaptcha(); // 生成新的验证码
            return false;
          }
        } else {
          this.$message.error('请输入正确的用户名、密码和验证码');
          return false;
        }
      });
    },
    closeDialog() {
      this.registerDialogVisible = false;
    },
    handleConfirm() {
      this.$refs['elForm'].validate(valid => {
        if (!valid) {
          this.$message.error("请确认注册信息！");
          return;
        }
        register(this.formData).then(res => {
          if (res.data.code == 200) {
            this.$message.success(res.data.msg);
          } else {
            this.$message.error(res.data.msg);
          }
        });
      })
    },
  },
  mounted() {
    this.generateCaptcha();
  }
};
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-image: url('~@/assets/background.png'); /* 设置背景图片 */
  background-size: cover; /* 背景图片覆盖整个容器 */
  background-position: center; /* 背景图片居中显示 */
  background-repeat: no-repeat; /* 背景图片不重复 */
}

.login-card {
  width: 400px;
  text-align: center;
  backdrop-filter: blur(5px); /* 添加毛玻璃效果，模糊半径为10px */
  background-color: rgba(255, 255, 255, 0.3); /* 背景颜色设置为半透明，增强毛玻璃效果 */
  border-radius: 25px; /* 如果需要，可以添加圆角 */
  padding: 20px; /* 根据需要调整内部间距 */
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); /* 可选，添加阴影以增强深度感 */
}

.login-title {
  margin-bottom: 20px;
  font-size: 24px;
}

.center-button {
  width: 100%;
}

.captcha-item {
  display: flex; /* 使用flex布局 */
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
}

.button-group {
  display: flex;
  justify-content: space-between;
}

.captcha-question {
  font-size: 16px; /* 增大字体大小 */
  color: #333; /* 字体颜色 */
  margin-left: -40px;
  padding: 0px 12px;
  background-color: #eef; /* 设置背景色 */
  border: 1px solid #ccc; /* 设置边框 */
  border-radius: 4px; /* 设置圆角 */
  display: inline-block; /* 让span元素在一行显示 */
}
</style>
